<template>
  <div class="main_spac1 maincl">
    <div class="main_white padding10">
      <div class="mainor_form">
        <el-form
          :inline="true"
          :model="form"
          class="demo-form-inline"
          ref="userListFrom"
          label-width="100px"
          id="form"
        >
          <el-form-item label="" prop="mode">
            <el-select
              v-model.trim="form.mode"
              placeholder="采购方式"
              class="wid100"
              @change="changeMode(1)"
              clearable
            >
              <el-option label="所有" value=""></el-option>
              <el-option
                v-for="(modeList, index) in list.modeList"
                :key="index"
                :label="modeList"
                :value="parseInt(index)"
              ></el-option>
            </el-select>
            <el-select
              v-model.trim="form.buyer_id"
              placeholder="采购员"
              class="wid220 marginLeft5s"
              v-show="form.mode == 1"
              filterable
              clearable
              @change="getArticleList"
            >
              <el-option label="所有" value=""></el-option>
              <el-option
                v-for="(buyer, index) in list.buyer"
                :key="index"
                :label="buyer"
                :value="parseInt(index)"
              ></el-option>
            </el-select>
            <el-select
              v-model.trim="form.supplier_id"
              placeholder="供应商"
              class="wid220 marginLeft5s"
              v-show="form.mode != 1 && form.mode"
              filterable
              clearable
              @change="getArticleList"
            >
              <el-option label="所有" value=""></el-option>
              <template v-if="form.mode == 2">
                <el-option
                  v-for="(supplier, index) in list.supplier"
                  :key="index"
                  :label="supplier"
                  :value="parseInt(index)"
                ></el-option>
              </template>
              <template v-if="form.mode == 3">
                <el-option
                  v-for="(supplier, index) in list.direct_supply"
                  :key="index"
                  :label="supplier"
                  :value="parseInt(index)"
                ></el-option>
              </template>
            </el-select>
            <el-select
              v-model.trim="form_mode_all"
              placeholder="所有"
              class="wid220 marginLeft5s"
              v-show="!form.mode"
              clearable
              @change="getArticleList"
            >
              <el-option label="所有" value=""></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="单据状态：" prop="status">
            <el-select
              v-model.trim="form.status"
              placeholder="单据状态"
              class="wid220"
              clearable
              @change="getArticleList"
            >
              <el-option label="所有" value=""></el-option>
              <el-option
                v-for="(statusList, index) in list.statusList"
                :key="index"
                :label="statusList"
                :value="parseInt(index + 1)"
              ></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="商品：">
            <el-autocomplete
              v-model="goods_spu_name"
              :fetch-suggestions="querysery"
              @select="handleSelect"
              class="wid220"
              placeholder="商品名称/助记码/编码"
              clearable
              @clear="
                () => {
                  this.form.goods_spu_id = '';
                  this.goods_spu_name = '';
                }
              "
            ></el-autocomplete>
          </el-form-item>
          <MainFormBtn @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="moredata">
            <el-button @click="exportMethodDia((exportFormVisible = true))">导出</el-button>
          </MainFormBtn>
          <div class="more el-form-item" @click="more">
            <span>更多</span>
            <i :class="[{ on: moredata }, ' el-icon-arrow-down']"></i>
          </div>
          <div class="clearfix"></div>
          <el-collapse-transition>
            <div v-show="moredata">
              <div>
                <el-form-item label="退货单号：" prop="order_sn">
                  <el-input
                    v-model.trim="form.order_sn"
                    placeholder="退货单号"
                    clearable
                    class="wid220"
                  ></el-input>
                </el-form-item>
                <el-form-item label="采购单号：" prop="purchase_order_sn">
                  <el-input
                    v-model.trim="form.purchase_order_sn"
                    placeholder="采购单号"
                    clearable
                    class="wid220"
                  ></el-input>
                </el-form-item>
                <el-form-item label="退货方式：" prop="type">
                  <el-select
                    v-model.trim="form.type"
                    placeholder="退货方式"
                    class="wid220"
                    clearable
                    @change="getArticleList"
                  >
                    <el-option label="所有" value=""></el-option>
                    <el-option
                      v-for="(typeList, index) in list.typeList"
                      :key="index"
                      :label="typeList"
                      :value="parseInt(index)"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="创建日期：" prop="createTime">
                  <el-date-picker
                    v-model="createTime"
                    type="daterange"
                    class="time220"
                    :editable="false"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                    :picker-options="pickerOptions"
                    @change="getArticleList"
                  />
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label="退货时间：" prop="establishTime">
                  <el-date-picker
                    v-model="establishTime"
                    type="daterange"
                    class="time220"
                    :editable="false"
                    unlink-panels
                    range-separator="至"
                    start-placeholder="开始日期"
                    end-placeholder="结束日期"
                    value-format="yyyy-MM-dd"
                    :clearable="false"
                    :picker-options="pickerOptions"
                    @change="getArticleList"
                  />
                </el-form-item>
                <div class="clearfix"></div>
                <el-form-item label=" ">
                  <MainFormBtn class="btn-bottom" @reset="reset" @getSearchFor="getSearchFor" :loading="listLoading" :showBtn="!moredata">
                    <el-button @click="exportMethodDia((exportFormVisible = true))">导出</el-button>
                  </MainFormBtn>
                </el-form-item>
              </div>
            </div>
          </el-collapse-transition>
        </el-form>
      </div>
      <div class="main-controls-wrap mg-t-4">
        <div>
          <router-link to="/purchasing/return/add" class="mainor_tea">创建退货单</router-link>
        </div>
      </div>
      <div class="main_table">
        <el-table
        ref="multipleTable"
        v-loading="listLoading"
        :data="list.list.data"
        element-loading-text="加载中"
        fit
        border
        highlight-current-row
        @selection-change="handleSelectionChange"
        :height="borderHeight"
        :header-cell-class-name="this.$verticaline"
        :header-cell-style="tableHeightStyle"
        @header-dragend="changeTableWidth"
        @row-dblclick="rowDblclick"
      >
        <el-table-column type="selection" align="center" />
        <el-table-column
          label="退货单号"
          prop="order_sn"
          :width="tableWidth[hash+'order_sn']"
        />

        <el-table-column
          label="采购单号"
          prop="purchase_sn"
          :width="tableWidth[hash+'purchase_sn']"
        >
          <template slot-scope="scope">{{
            scope.row.purchase ? scope.row.purchase.order_sn : ""
          }}</template>
        </el-table-column>

        <el-table-column
          label="采购方式"
          prop="byname"
          :width="tableWidth[hash+'byname']"
        >
          <template slot-scope="scope">
            <span :class="'modetype' + scope.row.type">
              {{ list.modeList[scope.row.mode] }}</span
            >
          </template>
        </el-table-column>

        <el-table-column
          label="采购员/供应商"
          prop="market"
          :width="tableWidth[hash+'market']"
        >
          <template slot-scope="scope">{{
            scope.row.mode == 1 ? scope.row.buyer.name : scope.row.supplier.name
          }}</template>
        </el-table-column>
        <el-table-column
          label="退货金额"
          prop="money"
          :width="tableWidth[hash+'money']"
        />
        <el-table-column
          label="单据状态"
          prop="status"
          :width="tableWidth[hash+'status']"
        >
          <template slot-scope="scope"
            ><span :class="'type' + scope.row.status">
              {{ list.statusList[scope.row.status] }}
            </span>
          </template>
        </el-table-column>
        <el-table-column
          label="创建时间"
          prop="created_at"
          :width="tableWidth[hash+'created_at']"
        >
          <template slot-scope="scope">
            {{ parseTime(scope.row.created_at, "{y}-{m}-{d}") }}
          </template>
        </el-table-column>
        <el-table-column
          label="退货时间"
          prop="return_time"
          :width="tableWidth[hash+'return_time']"
        >
          <template slot-scope="scope">
            {{
              scope.row.return_time
                ? parseTime(scope.row.return_time, "{y}-{m}-{d}")
                : ""
            }}
          </template>
        </el-table-column>
        <el-table-column
          label="管理操作"
          align="left"
          fixed="right"
          prop="operate"
          :width="tableWidth[hash+'operate'] || 240"
          class-name="main_hei"
          label-class-name="main-center"
        >
          <template slot-scope="scope">
            <router-link :to="'/purchasing/return/see/' + scope.row.id">
              <el-link type="success">查看</el-link>
            </router-link>

            <router-link :to="'/purchasing/return/edit/' + scope.row.id">
              <el-link type="warning" v-if="scope.row.status == 0"
                >审核</el-link
              >
            </router-link>

            <el-link
              type="danger"
              @click="delet(scope.$index, scope.row.id)"
              v-if="scope.row.status == 0"
              >取消</el-link
            >
            <el-link
              style="color: rgb(17, 138, 178)"
              @click="exportOrderiInfo(scope.row.id)"
              >导出</el-link
            >
          </template>
        </el-table-column>
        </el-table>
      </div>
      <div class="main_page boxdq">
        <div></div>
        <!-- 分页 -->
        <div class="main_page_r">
          <MainPagination
            :current-page="current.page"
            :page-sizes="[20, 30, 50, 100]"
            :page-size="limit"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalCount"
            background
            @size-change="changeLimit"
            @current-change="changePage"
          />
        </div>
      </div>

      <el-dialog
        title="导出"
        :visible.sync="exportFormVisible"
        class="main_dialog dialog500"
        @close="type = list.field"
      >
        <div class="export">你选择了{{ this.selectArr.length }}条数据</div>
        <div slot="footer" class="dialog-footer">
          <el-button @click="exportFormVisible = false">取 消</el-button>
          <el-button type="primary" @click="exportConfim" v-repeatClick
            >确 定</el-button
          >
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { mixins } from "@/mixins/index.js";
import {
  purchaseReturn_index,
  purchaseReturn_cancel,
  export_purchasing_return,
  export_select,
} from "@/api/purchasing/purchasingReturn";
import { goods_getGoodsSpu } from "@/api/currency";
import { apiUrl, objKeySort, Md5 } from "@/utils/public";
import { parseTime, exportMethod } from "@/utils/index";
import dateOption from "@/options/dateOption";
import MainPagination from '@/components/MainPagination'

export default {
  mixins: [mixins],
  components: { MainPagination },
  data() {
    return {
      // 时间
      parseTime,
      exportMethod,
      // 分页
      current: {
        page: 1,
        per_page: 20,
      },
      limit: 20,
      totalCount: 1,
      // 搜索
      form: {
        return_start_time: "",
        return_end_time: "",
        start_time: "",
        end_time: "",
        purchase_order_sn: "",
        type: null,
        order_sn: "",
        mode: null,
        status: null,
        buyer_id: null,
        supplier_id: null,
        name: "",
        goods_spu_id: "",
      },
      createTime: [],
      establishTime: [],
      pickerOptions: dateOption,
      // 更多
      moredata: false,
      // 列表数据
      list: {
        list: {
          data: [],
        },
      },
      listLoading: false,
      // 是否编辑
      isEdit: false,
      form_mode_all: null,
      // 全选
      selectArr: [],
      exportFormVisible: false,
      goods_spu_name: "",
    };
  },
  methods: {
    //  表格双击跳转详情页面
    rowDblclick(row, column, event) {
      this.$router.push('/purchasing/return/see/' + row.id)
    },
    // 点击键盘回车键时调用搜索回调
    startGetting() {
      this.getSearchFor();
    },
    // 点击搜索时将搜索条件进行折叠处理
    getSearchFor() {
      this.getArticleList();
    },
    handleSelect(item) {
      this.form.goods_spu_id = item.id;
    },
    //商品搜索
    querysery(queryString, cb) {
      if (!queryString) return cb([]);
      let arr = [];
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { name: queryString }
      );
      goods_getGoodsSpu(data).then((res) => {
        arr = res.data.goods.map((i) => {
          let title = i.spu_unit ? i.spu_unit.title : "";
          return {
            value: i.goods.name + `【${title}】`,
            id: i.id,
          };
        });
        cb(arr);
      });
    },
    // 搜索
    getArticleList() {
      this.current.page = 1;
      this.purchaseReturn_index();
    },
    reset() {
      this.$refs["userListFrom"].resetFields();
      this.goods_spu_name = "";
      this.form.goods_spu_id = "";
      this.createTime = [];
      this.establishTime = [];
      this.form.supplier_id = null;
      this.form.buyer_id = null;
      this.getArticleList();
    },
    // 监听全选
    handleSelectionChange(val) {
      this.selectArr = [];
      val.map((item) => {
        this.selectArr.push({ id: item.id });
      });
    },
    // 更多
    more() {
      this.moredata = !this.moredata;
    },
    // 分页
    changeLimit(pageSize) {
      this.current.per_page = pageSize;
      this.purchaseReturn_index();
    },
    changePage(page) {
      this.current.page = page;
      this.purchaseReturn_index();
    },
    // 采购方式切换
    changeMode(type) {
      switch (type) {
        case 1:
          this.form_mode_all = null;
          this.form.supplier_id = "";
          this.form.buyer_id = "";
          break;
      }
    },
    // 取消
    delet(index, id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, { id: id })) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      this.$confirm("是否取消退货单?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          purchaseReturn_cancel(data).then((res) => {
            if (res.errcode == 0) {
              this.$message({
                message: "取消成功",
                type: "success",
              });
              this.purchaseReturn_index();
            } else {
              this.$message.error(res.errmsg);
            }
          });
        })
        .catch(() => {});
    },
    // 列表
    purchaseReturn_index() {
      this.listLoading = true;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(
              Object.assign(apiUrl().name, this.list_form(), this.current)
            ) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        this.list_form(),
        this.current
      );
      purchaseReturn_index(data).then((res) => {
        this.listLoading = false;
        if (res.errcode == 0) {
          this.list = res.data;
          this.totalCount = res.data.list.total;
        } else {
          this.$message.error(res.errmsg);
        }
      });
    },
    list_form() {
      let form = JSON.parse(JSON.stringify(this.form));
      form.start_time = this.createTime[0] ? this.createTime[0] : "";
      form.end_time = this.createTime[1] ? this.createTime[1] : "";
      form.return_start_time = this.establishTime[0]
        ? this.establishTime[0]
        : "";
      form.return_end_time = this.establishTime[1] ? this.establishTime[1] : "";

      return form;
    },

    // 导出
    exportOrderiInfo(id) {
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name)) + apiUrl().appsecret
          ),
        },
        apiUrl().name,
        { id: id }
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_purchasing_return(data)
        .then((res) => {
          this.exportMethod(res, "采购退货单", notify);
        })
        .catch(() => {
          this.$message.error("导出失败");
        });
    },

    //订单导出
    exportMethodDia() {
      if (this.selectArr.length > 0) {
        this.exportFormVisible = true;
      } else {
        this.exportConfim();
      }
    },
    // 导出确认
    exportConfim() {
      let form = JSON.parse(JSON.stringify(this.form));
      let ids = [];
      if (this.selectArr.length > 0) {
        this.selectArr.forEach((item) => {
          ids.push(item.id);
        });
      }
      ids = ids.join("-");
      form.ids = ids;
      let data = Object.assign(
        {
          sign: Md5(
            objKeySort(Object.assign(apiUrl().name, this.current)) +
              apiUrl().appsecret
          ),
        },
        apiUrl().name,
        form,
        this.current
      );
      const notify = this.$notify.info({
        title: "开始导出...",
        type: "success",
        duration: 0,
      });
      export_select(data).then((res) => {
        this.exportMethod(res, "采购退货", notify);
      });
      this.exportFormVisible = false;
    },
  },
  created() {
    // 列表
    this.getNumerical(220);
    this.purchaseReturn_index();
  },
};
</script>
<style lang="scss" scoped>
@import "@/styles/variables.scss";
.mainor_form form {
  width: 100%;
}

// 单据状态
.type1 {
  color: $green;
}
.type2 {
  color: $colour_red;
}
.type0 {
  color: $colour_orange;
}
// 订单状态
.order1 {
  color: $order_color1;
}
.order2 {
  color: $order_color2;
}
.order3 {
  color: $order_color3;
}
.order4 {
  color: $order_color4;
}

.modetype2 {
  color: #03a98e;
}
.modetype1 {
  color: #118ab2;
}
.modetype3 {
  color: #aacd6e;
}

.wid100 {
  width: 100px;
  /deep/ .el-input__inner {
    border: none;
  }
}
.marginLeft5s {
  margin-left: -5px;
}
.el-form-item--small.el-form-item {
  margin-bottom: 12px;
}
</style>
